package cn.com.hp.feature.onfig;

import cn.com.hp.feature.util.ToolUtil;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author hongjuzhu
 * @date 2022/3/9
 */
@Configuration
@MapperScan("com.marketplace.*.repository")
public class MybatisPlusConfig {
    private UserProperties userProperties = new UserProperties();

    private static String TENANT_ID ="tenantId";
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        // 如果用了分页插件注意先 add TenantLineInnerInterceptor 再 add PaginationInnerInterceptor
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //此处逻辑参考mybatis-plus多租户控制逻辑
        if (Boolean.TRUE.equals(userProperties.getEnable())) {
            interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
                @Override
                public Expression getTenantId() {
                    if (ToolUtil.isEmpty(UserProperties.getCurrentUserId(TENANT_ID))){
                        return new StringValue("HP");
                    }else {
                        return new StringValue(UserProperties.getCurrentUserId(TENANT_ID));
                    }
                }
                @Override
                public String getTenantIdColumn() {
                    return userProperties.getColumn();
                }

                // 这是 default 方法,默认返回 false 表示所有表都需要拼bu查询条件
                //过滤不需要bu查询的表,暂时屏蔽拦截
                @Override
                public boolean ignoreTable(String tableName) {
                    return userProperties.getIgnoreTables().stream().anyMatch(
                            (t) -> t.equalsIgnoreCase(tableName)
                    );
                }
            }));
        }
        PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor();
        interceptor.addInnerInterceptor(paginationInterceptor);
        return interceptor;
    }
}
